package com.sunyard.utils.easyexcel.write;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.sunyard.utils.easyexcel.ExcelStyle;
import com.sunyard.utils.easyexcel.style.MyCellStyle;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;

import java.lang.reflect.Field;

/**
 * @author ：kaik.lou
 * @date ： 2021/1/15 8:56
 * @description：单元格格式
 */
@Slf4j
public class ExcelStyleAnnotationCellWriteHandler extends HorizontalCellStyleStrategy {

    private Class c;

    ExcelStyleAnnotationCellWriteHandler(Class c, WriteCellStyle headWriteCellStyle, WriteCellStyle contentWriteCellStyle) {
        super(headWriteCellStyle, contentWriteCellStyle);
        this.c = c;
    }

    @Override
    protected void setContentCellStyle(Cell cell, Head head, Integer relativeRowIndex) {
        try {
            Field declaredField = c.getDeclaredField(head.getFieldName());
            ExcelStyle annotation = declaredField.getAnnotation(ExcelStyle.class);
            if (annotation != null) {
                Workbook wb = cell.getSheet().getWorkbook();
                DataFormat df = wb.createDataFormat(); // 此处设置数据格式

                CellStyle cellStyle = wb.createCellStyle();
                MyCellStyle cellType = annotation.cellType();
//                cellStyle.setDataFormat((short) 3);
                //整数："0_ "
                //小数："0.00_ " （精确到几位就加几个0）
                Font contentWriteFont = wb.createFont();
                contentWriteFont.setFontHeightInPoints((short) 12);
                cellStyle.setDataFormat(df.getFormat(cellType.getContext()));// 最关键的是'_ '，最后有个空格别忘了，空格是必须的
                cellStyle.setFont(contentWriteFont);
                cellStyle.setBorderBottom(BorderStyle.THIN);
                cellStyle.setBorderLeft(BorderStyle.THIN);
                cellStyle.setBorderTop(BorderStyle.THIN);
                cellStyle.setBorderRight(BorderStyle.THIN);
                cellStyle.setAlignment(HorizontalAlignment.CENTER);
                cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
                cell.setCellStyle(cellStyle);
            } else {
                super.setContentCellStyle(cell, head, relativeRowIndex);
            }
        } catch (NoSuchFieldException e) {
            log.error("ExcelStyleAnnotationCellWriteHandler error{0}", e);
        }

    }

}
